package com.xiaomiMall.mange.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.xiaomiMall.mange.domain.MallLoginBody;
import com.xiaomiMall.mange.domain.MallLoginUser;
import com.xiaomiMall.mange.domain.MallUser;
import com.xiaomiMall.mange.domain.vo.Address;
import com.xiaomiMall.mange.domain.vo.Notepad;
import com.xiaomiMall.mange.domain.vo.Order;
import com.xiaomiMall.mange.domain.vo.OrderShow;
import com.xiaomiMall.mange.service.Impl.MallLoginServiceImpl;
import com.xiaomiMall.mange.service.Impl.MallTokenServiceImpl;
import com.xiaomiMall.mange.service.Impl.MallUserServiceImpl;
import io.lettuce.core.dynamic.annotation.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/api")
public class MallUserController extends BaseController {

    @Autowired
    private MallUserServiceImpl userService;

    @Autowired
    private MallTokenServiceImpl mallTokenService;

    @Autowired
    private MallLoginServiceImpl loginService;

    //修改密码
    @PostMapping("/updatePassword")
    public AjaxResult updatePassword(HttpServletRequest request, @RequestBody HashMap<String,String> password) {
        AjaxResult ajax = null;
        MallLoginUser mallLoginUser = mallTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(mallLoginUser)) {
            MallUser loginUser = mallLoginUser.getMallUser();
            if (SecurityUtils.matchesPassword(password.get("oldPass"),loginUser.getPassword())) {
                loginUser.setPassword(SecurityUtils.encryptPassword(password.get("newPass")));
                if (userService.updatePassword(loginUser)) {
                    ajax = AjaxResult.success("success");
                } else {
                    ajax = AjaxResult.error("更改失败，请稍后重试");
                }
            } else {
                ajax = AjaxResult.error("原密码错误，请重试，或联系管理员重置密码");
            }
        } else {
            ajax = AjaxResult.error("更改失败，请稍后重试");
        }
        return ajax;
    }

    // 获取收货地址
    @GetMapping("/getAddress")
    public AjaxResult getAddress(HttpServletRequest request) {
        AjaxResult ajax = AjaxResult.success();
        MallLoginUser mallLoginUser = mallTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(mallLoginUser)) {
            List<Address> address = userService.getAddress(mallLoginUser.getUserId());
            ajax.put("address", address);
        } else {
            ajax = AjaxResult.error(401,"登陆状态已过期");
        }
        return ajax;
    }

    // 新增/修改收货地址
    @PostMapping("/updateAddress")
    public AjaxResult addAddress(HttpServletRequest request, @RequestBody Address address) {
        AjaxResult ajax = null;
        String message = "";
        MallLoginUser mallLoginUser = mallTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(mallLoginUser)) {
            ajax = AjaxResult.success();
            if (StringUtils.isNotNull(address.getId())) {
                // 这里是修改地址的处理
                message = userService.modifyAddress(address) ? "修改成功" : "修改失败，请稍后重试";
            } else {
                // 这里是新增地址的处理
                address.setUserId(mallLoginUser.getUserId());
                message = userService.addAddress(address) ? "添加成功" : "添加失败，请稍后再试";
            }
            ajax.put("message", message);
        } else {
            ajax = AjaxResult.error(401,"登陆状态已过期");
        }
        return ajax;
    }

    //删除收货地址
    @PostMapping("/deleteAddress")
    public AjaxResult deleteAddress(HttpServletRequest request, @RequestBody int id) {
        AjaxResult ajax = AjaxResult.success();
        MallLoginUser mallLoginUser = mallTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(mallLoginUser)) {
            String message = userService.deleteAddress(mallLoginUser.getUserId(), id) ? "删除成功" : "删除失败，请稍后再试";
            ajax.put("message", message);
        } else {
            ajax = AjaxResult.error(401,"登陆状态已过期");
        }
        return ajax;
    }

    @GetMapping("/getRestMoney")
    public AjaxResult getRestMoney(HttpServletRequest request) {
        AjaxResult ajax = AjaxResult.success();
        MallLoginUser loginUser = mallTokenService.getLoginUser(request);
        if (StringUtils.isNull(loginUser)) {
            return AjaxResult.error(401,"登陆状态已过期");
        } else {
            MallUser mallUser = userService.selectMallUserById(loginUser.getUserId());
            ajax.put("restMoney", mallUser.getWallet());
        }
        return ajax;
    }


    // 我的订单
    @GetMapping("/getOrders")
    public AjaxResult getOrders(HttpServletRequest request, @Param("status") Integer status) {
        AjaxResult ajax = AjaxResult.success();
        MallLoginUser mallLoginUser = mallTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(mallLoginUser)) {
            startPage();
            List<OrderShow> orderShowList = userService.getOrderShow(mallLoginUser.getUserId(), status);
            ajax.put("orders", getDataTable(orderShowList));
        } else {
            ajax = AjaxResult.error(401,"登陆状态已过期");
        }
        return ajax;
    }

    // 查找订单
    @PostMapping("/findOrders")
    public AjaxResult findOrders(HttpServletRequest request,@RequestBody HashMap<String,String> query) {
        AjaxResult ajax = AjaxResult.success();
        MallLoginUser mallLoginUser = mallTokenService.getLoginUser(request);
        Long orderId = null;
        if (StringUtils.isNotNull(mallLoginUser)) {
            try {
                orderId = Long.parseLong(query.get("inputContent")); // 传来的是订单号
            } catch (Exception e) {
                System.out.println(e); // 传来的是商品名
            }
            if (StringUtils.isNotNull(orderId)) {
                startPage();
                OrderShow orderShow = userService.getOrderShowByNum(mallLoginUser.getUserId(), orderId.toString());
                List<OrderShow> orderShows = new ArrayList<>();
                orderShows.add(orderShow);
                ajax.put("orders", orderShows);
            } else {
                startPage();
                List<OrderShow> orderShowByNameList = userService.getOrderShowByName(mallLoginUser.getUserId(), query.get("inputContent"));
                ajax.put("orders", orderShowByNameList);
            }
        } else {
            ajax = AjaxResult.error(401,"登陆状态已过期");
        }
        return ajax;
    }

    // 删除订单
    @PostMapping("/deleteOrder")
    public AjaxResult deleteOrder(HttpServletRequest request,@RequestBody String orderNumber) {
        AjaxResult ajax = AjaxResult.success();
        MallLoginUser mallLoginUser = mallTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(mallLoginUser)) {
            String message = userService.updateOrderStatus(orderNumber, 3) ? "删除成功" : "删除失败，请稍后再试";
            ajax.put("message", message);
        } else {
            ajax = AjaxResult.error(401,"登陆状态已过期");
        }
        return ajax;
    }

    // 钱包充值
    @PostMapping("/charge")
    public AjaxResult charge(HttpServletRequest request,@RequestBody HashMap<String,String> amount){
        AjaxResult ajax = AjaxResult.success();
        MallLoginUser mallLoginUser = mallTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(mallLoginUser)) {
            String note = "申请充值" + amount.get("count");
            Notepad notepad = new Notepad(null,mallLoginUser.getUserId(),new Date(),note,0);
            String message = userService.insertNotepad(notepad) ? "申请成功，请等待充值完成" : "申请失败，请稍后再试";
            ajax.put("message", message);
        } else {
            ajax = AjaxResult.error(401,"登陆状态已过期");
        }
        return ajax;
    }

    // 获取消息通知
    @GetMapping("/getMessage")
    public AjaxResult getMessage(HttpServletRequest request,@Param("status") Integer status) {
        AjaxResult ajax = AjaxResult.success();
        MallLoginUser loginUser = mallTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            startPage();
            List<Notepad> notepads = userService.selectNotepadByUserId(loginUser.getUserId(), status);
            ajax.put("notepads", getDataTable(notepads));
        } else {
            ajax = AjaxResult.error(401,"登陆状态已过期");
        }
        return ajax;
    }

    // 完成付款
    @PostMapping("/payMoney")
    public AjaxResult payMoney(HttpServletRequest request, @RequestBody HashMap<String,Long> data) {
        AjaxResult ajax = AjaxResult.success();
        MallLoginUser loginUser = mallTokenService.getLoginUser(request);
        if (StringUtils.isNull(loginUser)) {
            return AjaxResult.error(401,"登陆状态已过期");
        } else {
            MallUser user = loginUser.getMallUser();
            MallLoginBody loginBody = new MallLoginBody(user.getEmail(),data.get("password").toString(),null);
            if (StringUtils.isNull(loginService.checkPassword(loginBody))) {
                return ajax.put("message", "密码错误");
            } else {
                List<Order> orderList = userService.selectOrderByOrderNum(user.getId(), data.get("orderNum"));
                float money = orderList.get(0).getTotalPrice();
                Boolean paySuccess = userService.reduceWallet(user.getId(), money);
                String message = paySuccess ? "付费成功" : "余额不足，请充值后再来";
                ajax.put("message", message);
                if (paySuccess) {
                    userService.updateOrderStatus(data.get("orderNum").toString(),1);
                }
            }
        }
        return ajax;
    }

}

